package cn.linran.user.controller;

import cn.linran.basic.exception.BusinessException;
import cn.linran.user.dto.RegisterDto;
import cn.linran.user.service.IUserService;
import cn.linran.user.domain.User;
import cn.linran.user.query.UserQuery;
import cn.linran.basic.util.JsonResult;
import cn.linran.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
* 后端接口类；
*/
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    public IUserService userService;


    /**
     * 手机验证码注册接口（组测按钮）
     */
    @PostMapping("/phoneRegister")
    public JsonResult phoneRegister(@RequestBody RegisterDto dto){
        try {
            userService.phoneRegister(dto);
            return JsonResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return JsonResult.me().setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("网络异常，稍后重试！");
        }
    }
    /**
     * 接口：添加或修改
     * @param user  传递的实体
     * @return JsonResult 响应给前端
     */
    @PutMapping
    public JsonResult addOrUpdate(@RequestBody User user){
        try {
            if(
                user.getId()!=null)
                userService.update(user);
            else
                userService.save(user);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("“操作失败”");
        }
    }

    /**
    * 接口：删除
    * @param id
    * @return JsonResult 响应给前端
    */
    @DeleteMapping(value="/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            userService.remove(id);
            return JsonResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return JsonResult.me().setMsg("“删除失败”");
        }
    }

    /**
    * 接口：批量删除
    * @param ids
    * @return JsonResult 响应给前端
    */
    @PatchMapping
    public JsonResult patchDelete(@RequestBody List<Long> ids){
        try {
                userService.batchDel(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("“批量删除失败”");
        }
    }

    /**
    * 接口：查询单个对象
    * @param id
    */
    @GetMapping("/{id}")
    public User findOne(@PathVariable("id")Long id) {
        return userService.loadById(id);
    }


    /**
    * 接口：查询所有
    * @return
    */
    @GetMapping
    public List<User> findAll(){
        return userService.loadAll();
    }


   /**
    * 接口：分页查询或高级查询
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery query) {
        return userService.pageQuery(query);
    }
}
